"""Create GO Analysis

.. helpdoc::

"""

"""<widgetXML>
    <name>Create GO Analysis</name>
    <icon>Default.png</icon>
    <tags> 
        <tag>Microarray</tag> 
    </tags>
    <summary></summary>
    <author>
        <authorname>Kyle R Covington</authorname>
        <authorcontact>kyle@red-r.org</authorcontact>
    </author>
</widgetXML>
"""

"""
<name>Create GO Analysis</name>
<tags>Microarray</tags>
"""

from OWRpy import *
import globalData

from libraries.base.signalClasses.RDataFrame import RDataFrame as redRRDataFrame
from libraries.affy.signalClasses.RTopGOData import RTopGOData as redRRTopGOData
from libraries.base.signalClasses.RList import RList as redRRList
from libraries.base.signalClasses.RVector import RVector as redRRVector


from libraries.base.qtWidgets.groupBox import groupBox as redRGroupBox
from libraries.base.qtWidgets.widgetBox import widgetBox as redRWidgetBox
from libraries.base.qtWidgets.commitButton import commitButton as redRCommitButton
from libraries.base.qtWidgets.comboBox import comboBox as redRComboBox
from libraries.base.qtWidgets.radioButtons import radioButtons as redRRadioButtons
from libraries.base.qtWidgets.checkBox import checkBox as redRcheckBox
from libraries.base.qtWidgets.spinBox import spinBox as redRspinBox
from libraries.base.qtWidgets.lineEdit import lineEdit as redRlineEdit
from libraries.base.qtWidgets.widgetLabel import widgetLabel as redRwidgetLabel
from libraries.base.qtWidgets.button import button as redRbutton

class redRCreateGOAnalysis(OWRpy):
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)

        self.geneList = None
        self.chipType = None
        self.ontologies = ["BP", "MF", "CC"]
        self.setRvariableNames(['topGOData','GOdb','db','universe','allGenes','tests','results'])
        self.require_librarys(['topGO','ALL'])

        self.R('library(ALL)')
        self.R('data(ALL)')
        self.R('data <- data(geneList)')
        self.geneList = 'data'
        self.chipType = self.R('annotation(ALL)')
        self.parentEset = 'ALL'
        
        """.. rrsignals::"""
        self.inputs.addInput("genelist", "Gene List", redRRList, self.process)
        
        """.. rrsignals::"""
        self.outputs.addOutput('od1', 'topGO Data', redRRTopGOData) #[("data.frame", rdf.RDataFrame)]

        dataBox = redRWidgetBox(self.controlArea)
        self.chipTypeBox = redRWidgetBox(dataBox)
        
        self.chipTypeWarning = redRwidgetLabel(self.chipTypeBox,label='The chip type was not recognized. Please type the name of the chip. Examples: hgu133b, hgu133plus2, hgu95av2 ...',wordWrap=True)
        self.chipTypeWarning.hide()
        box = redRWidgetBox(self.chipTypeBox,orientation='horizontal')
        self.chipTypeEdit = redRlineEdit(box ,label='Chip Type')
        # redRbutton(box, label='Load Chip Annotations',callback=self.loadChipType)
        
        self.ontology = redRcheckBox(dataBox, buttons=self.ontologies, label='Ontology',
        setChecked=self.ontologies, orientation='horizontal')
        self.nodeSize = redRspinBox(dataBox,label='Trim Node Size',value=10,max=500,min=0)
        self.probeIDColumn = redRComboBox(dataBox,label="Gene List of Interest")
        redRCommitButton(self.bottomAreaRight,label='Create GO Data',callback=self.commitFunction)

    def process(self,data):
        if not data: 
            self.probeIDColumn.clear()
            return
        self.geneList = data.getData()
        self.parentEset = data.getDataParent()
        chipType = globalData.getGlobalData('Chip Type')
        print 'adasfadf', self.chipType
        if len(chipType) ==1:
            self.chipTypeEdit.setText(chipType[0])
            self.loadChipType()            
        else:
            self.chipTypeWarning.show()
            
        names = self.R('names(%s)' % self.geneList, wantType='list')
        self.probeIDColumn.clear()
        self.probeIDColumn.addItems(names)
    
    def loadChipType(self):
        chipType = str(self.chipTypeEdit.text())
        if chipType =='': return
        # self.require_librarys(chipType + '.db')
        try:
            if not self.require_librarys([chipType + '.db']): 
                raise Exception, 'R Libraries not loaded'
        except:
            self.chipTypeWarning.show()
            return 
    
    def getChipType(self): 
        chipType = self.chipTypeEdit.text()
        self.R('%s <- paste("%s", "db", sep = ".")' % (self.Rvariables['db'],chipType))
        #self.R('%s <- paste("%s", "GO", sep = "")' % (self.Rvariables['GOdb'],chipType))
        self.R('%s <- mappedkeys(%s)' % (self.Rvariables['allGenes'], chipType+'GO'))
        self.R('%s <- as.factor(c(rep(0,length(mappedkeys(%s)))))' % (
        self.Rvariables['universe'], chipType+'GO'))
        self.R('names(%s) <- %s' % (
        self.Rvariables['universe'],self.Rvariables['allGenes']))
        self.R('levels(%s) <- c(0,1)' % self.Rvariables['universe'])

    def updateGeneList(self):
        column = self.probeIDColumn.currentText()
        if not column or column == '':
            return
        self.R('%s[names(%s) %%in%% %s$%s] = 1' % (
        self.Rvariables['universe'],self.Rvariables['universe'],self.geneList,column))
        
        self.R('%s <- updateGenes(%s,%s)' % (
        self.Rvariables['topGOData'],self.Rvariables['topGOData'],self.Rvariables['universe']))
        
    def commitFunction(self):
        chipType = str(self.chipTypeEdit.text())
        ontologies = self.ontology.getChecked()
        if not self.geneList or chipType == '' or len(ontologies) ==0:
            return
        
        self.loadChipType()
        self.getChipType()
        nodeSize = self.nodeSize.value()
        
        self.R('%s = NULL' % self.Rvariables['topGOData'])
        
        for ontology in ontologies:
            self.R('%s$%s <- new("topGOdata", description = "session", ontology = "%s", allGenes = %s, nodeSize = %d, annot = annFUN.db, affyLib = %s)' % (
        self.Rvariables['topGOData'],ontology, ontology,self.Rvariables['universe'],
        nodeSize,self.Rvariables['db']))
        
        sendData = redRRTopGOData(self, data = self.Rvariables['topGOData'])
        self.rSend("od1", sendData)

